<?php
class Model_Tool_DataMapper {
	protected $_dbAdapter;
	public function __construct(){
		$this->_dbAdapter = Zend_Db_Table::getDefaultAdapter();
	}

	public static function getInstance() { return new self(); }

	/**
	 * Typically used in <select>-box-value querying
	 * Map 2 field of a rowset (or an array)
	 *     to form new array
	 *     with the format of
	 *         array(
	 *             key => value,
	 *             key => value
	 *         )
	 * @param Zend_Db_Table_Abstract|Zend_Db_Select|array|string|Zend_Db_Expr $data
	 * @param string $keyField
	 * @param string $valueField
	 * @param array $currentArray
	 * @return array mappedData
	 */
    public function mapKeyValue($data, $keyField='id', $valueField='name', $currentArray=array()) {
    	if(!is_array($data)) {
    	    if($data instanceof Zend_Db_Table_Abstract) {
    	    	$data = $data->fetchAll();
    	    } else if ($data instanceof Zend_Db_Select) {
	            $data = $data->query(Zend_Db::FETCH_ASSOC);
    	    } else if (is_string($data)) {
    	        $data = $this->_dbAdapter->select($data)->query()->fetchAll();
    	    } else if ($data instanceof Zend_Db_Expr) {
    	    	$data = $this->_dbAdapter->fetchAll($data . '');
    	    }
        }

        $mappedData = is_array($currentArray)
                      ? $currentArray
                      : array();
        foreach ($data as $r) {
        	if (intval($r[$keyField])>=0){
        	   $mappedData[$r[$keyField]] = $r[$valueField];
        	}
        }
        return $mappedData;
    }
    /**
     * Get Value in valueField by specified keyValue of keyField
     * @param Zend_Db_Table_Abstract|Zend_Db_Select|array|string(sql query) $data
     * @param string $valueField
     * @param string $keyValue
     * @param string $keyField [optional] [default='id']
     */
    public function getValueByKey($data, $valueField, $keyValue, $keyField='id') {
    	if($data instanceof Zend_Db_Table_Abstract) {
            $s = $data->select(true)
                      ->columns(new Zend_Db_Expr($valueField . ' AS v'))
                      ->where($keyField . ' = ?', array($keyValue));
        } else if ($data instanceof Zend_Db_Select) {
        	$s = $data->columns(new Zend_Db_Expr($valueField . ' AS v'))
        	          ->where($keyField . ' = ?', array($keyValue));
        } else if (is_string($data)) {
        	$s = 'SELECT ' . $valueField . ' AS v
        		  FROM '   . $data       . '
        	      WHERE '  . $keyField   . ' = ' . $this->_dbAdapter->quote($keyValue);
        }

        $r = null;
        if($s) { $r = $this->_dbAdapter->fetchRow($s); }

        return $r ? $r['v'] : null;
    }

    public function arrayMap($array, $map=null) {
        if(!is_array($map)) {
            return $array;
        }
        $arr = array();
        foreach ($map as $k => $v) {
            $arr[$v] = isset($array[$k])
                       ? $array[$k]
                       : null;
        }
        return $arr;
    }
}
